package mx.netbrain.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.primefaces.model.UploadedFile;

import mx.netbrain.bean.InstallBean;
import mx.netbrain.dao.TypeFileDao;
import mx.netbrain.dao.impl.TypeFileDaoImpl;
import mx.netbrain.model.Type;
import mx.netbrain.model.TypeField;

public class TypeFileController {

	private static String PATH;

	public static List<TypeField> completeType(String query,
			List<TypeField> listType) {
		List<TypeField> suggestions = new ArrayList<TypeField>();
		for (TypeField p : listType) {
			if (p.getDescription().startsWith(query))
				suggestions.add(p);
		}
		return suggestions;
	}

	public static void uploadValidate(UploadedFile fileUpload) {
		InstallBean installBean = new InstallBean();
		PATH = installBean.getEstructure();
		if (fileUpload != null) {
			System.out.println(fileUpload.getFileName());
			String ext = fileUpload.getFileName();
			StringTokenizer delimitador = new StringTokenizer(ext, ".");
			try {
				transferFile(fileUpload.getFileName(),
						fileUpload.getInputstream(), fileUpload);
			} catch (IOException e) {
				FacesContext context = FacesContext.getCurrentInstance();
				context.addMessage(null, new FacesMessage("Wrong",
						"Error al cargar archivo."));
			}
			Type type = new Type();
			System.out.println(delimitador);
			type.setExtension(delimitador.nextToken().trim());
			type.setName(fileUpload.getFileName());
			type.setRute(PATH + "icon/");
			type.setType(fileUpload.getContentType());
			TypeFileDao typeFileDao = new TypeFileDaoImpl();
			typeFileDao.save(type);
			FacesContext context = FacesContext.getCurrentInstance();
			context.addMessage(null,
					new FacesMessage("Succefull", fileUpload.getFileName()
							+ " se cargo correctamente!"));

		} else {
			FacesContext context = FacesContext.getCurrentInstance();
			context.addMessage(null, new FacesMessage("Wrong",
					"Seleccione un archivo."));
		}
	}

	public static void transferFile(String fileName, InputStream in,
			UploadedFile fileUpload) {
		InstallBean installBean = new InstallBean();
		PATH = installBean.getEstructure();
		try {
			OutputStream out = new FileOutputStream(new File(PATH + "icon/"
					+ fileName));
			int reader = 0;
			byte[] bytes = new byte[(int) fileUpload.getSize()];
			while ((reader = in.read(bytes)) != -1) {
				out.write(bytes, 0, reader);
			}
			in.close();
			out.flush();
			out.close();
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}

}
